package com.learn.swagger.app.service.impl;

import com.learn.swagger.config.CusSwaggerProperties;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.net.URI;
import java.util.*;

/**
 * @author PC
 * swagger接口实现类
 */
@Primary
@Service
public class SwaggerServiceImpl implements SwaggerResourcesProvider {
    private final static String API_DOCS_URL_FORMAT = "/%s/v2/api-docs";

    private final static String SWAGGER_VERSION = "2.0";

    private final DiscoveryClient discoveryClient;

    @Autowired
    public SwaggerServiceImpl(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
    }

    private CusSwaggerProperties cusSwaggerProperties;

    @Autowired
    public void setSwaggerProperties(CusSwaggerProperties cusSwaggerProperties) {
        this.cusSwaggerProperties = cusSwaggerProperties;
    }

    @Override
    public List<SwaggerResource> get() {
        List<String> instanceIdList = discoveryClient.getServices();
        if (CollectionUtils.isEmpty(instanceIdList)) {
            return new ArrayList<>();
        }
        List<SwaggerResource> swaggerResourceList = new ArrayList<>();
        for (String instanceId : instanceIdList) {
            if (CollectionUtils.containsAny(cusSwaggerProperties.getSkipPath(), instanceId)) {
                continue;
            }
            SwaggerResource swaggerResource = new SwaggerResource();
            swaggerResource.setName(instanceId);
            swaggerResource.setSwaggerVersion(SWAGGER_VERSION);
            swaggerResource.setUrl(pendingUrl(instanceId));
            swaggerResourceList.add(swaggerResource);
        }
        return swaggerResourceList;
    }

    private String pendingUrl(String instanceId) {
        if (StringUtils.isEmpty(instanceId)) {
            return StringUtils.EMPTY;
        }
        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances(cusSwaggerProperties.getGatewayRouteName());
        if (CollectionUtils.isEmpty(serviceInstanceList)) {
            return StringUtils.EMPTY;
        }
        URI gatewayUri = serviceInstanceList.get(0).getUri();
        if (Objects.isNull(gatewayUri)) {
            return StringUtils.EMPTY;
        }
        return gatewayUri + String.format(API_DOCS_URL_FORMAT, instanceId);
    }
}
